﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using smartcrm.Models;
using smartcrm.Utilities;

namespace smartcrm.Controllers
{
    public class AccountController : BaseController
    {
        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            User user = new User();
            if (Request.Cookies["UserId"] != null)
            {
                user.UserId = Request.Cookies["UserId"].Value;
            }
            if (IS_DEMO)
            {
                user.UserId = "100103"; 
            }

            return View(user);
        }

        [HttpPost]
        public JsonResult Login(User model, string returnUrl)
        {
            JsonResult result = new JsonResult();
            bool loginSuccess = true;
            User user = Context.User.FirstOrDefault(m => m.UserId == model.UserId);
            if (user == null)
            {
                loginSuccess = false;
            }
            else
            {
                if (MD5Utility.MD5Encrypt(model.Password) != user.Password)
                {
                    loginSuccess = false;
                }
            }

            if (loginSuccess)
            {
                HttpCookie cookie = new HttpCookie("UserId");
                cookie.Value = model.UserId;
                cookie.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(cookie);

                LoginUser loginUser = new LoginUser();
                loginUser.UserId = user.UserId;
                loginUser.UserName = user.UserName;
                loginUser.CompanyNo = user.CompanyNo;
                loginUser.Permissions = user.Permissions;
                if (!string.IsNullOrEmpty(user.Permissions))
                {
                    loginUser.PermissionList = user.Permissions.Split(',').ToList();
                }
                Session[PORTAL_LOGIN_USER] = null;
                Session[LOGIN_USER] = loginUser;

                result.Data = new { code = 0 };
            }
            else
            {
                result.Data = new { code = 1 };
            }
            return result;
        }

        public ActionResult LogOut()
        {
            Session[LOGIN_USER] = null;
            return RedirectToAction("Index", "Home");
        }
    }
}
